//
//  MainViewController.m
//  CoolFM
//
//  Created by 曹曹 on 16/8/27.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "MainViewController.h"
#import "CFMacro.h"
#import "UIView+Frame.h"
#import "GX_Button.h"
#import "GXNetTool.h"
#import "UIImageView+WebCache.h"

#import "MyViewController.h"
#import "DJViewController.h"
#import "RadioViewController.h"
#import "ProgramViewController.h"
#import "MineCollectionViewCell.h"
#import "DJCollectionViewCell.h"
#import "ProgramCollectionViewCell.h"
#import "RadioCollectionViewCell.h"
// model
#import "DJRootModel.h"
#import "DJLocationRoot.h"
#import "RadioRootModel.h"
#import "ProgramModel.h"

#import "PlayerModel.h"
#import "PlayerList.h"
#import "CommentBar.h"

#import "PlayerViewController.h"
#import "PlayBarView.h"
#import "PlayBarDetailView.h"
#import "AlbumRecord_Plays.h"
#import "AlbumRecord.h"

// collectionView cell
#define kMineCollectionViewCell @"MineCollectionViewCell"
#define kDJCollectionViewCell @"DJCollectionViewCell"
#define kRadioCollectionViewCell @"RadioCollectionViewCell"
#define kProgramCollectionViewCell @"ProgramCollectionViewCell"

@interface MainViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray<NSString *> *topTitles;
@property (nonatomic, strong) UIView *topView;
//model
@property (nonatomic, strong) DJRootModel *djContent;
@property (nonatomic, strong) DJLocationRoot *djLocation;
@property (nonatomic, strong) RadioRootModel *radio;
@property (nonatomic, strong) ProgramModel *program;
// 评论条
@property (nonatomic, strong) CommentBar *commentBar;
// 播放条
@property (nonatomic, strong) PlayBarView *playerView;
// 播放列表
@property (nonatomic, strong) PlayBarDetailView *playListMenu;
// 遮挡view
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) AlbumRecord_Plays *record_plays;

@end

@implementation MainViewController

#warning vc将要出现时改变 CollectionView的偏移量, 使第二页首先显示, 问题是, pop回主vc后依然在第二页, 而不是push的那个页面
#warning MainViewController send noti
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self.collectionView setContentOffset:CGPointMake(SCREEN_WIDTH, 0)];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showPlayerView"
                                                        object:@"playerView"
                                                      userInfo:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    [self setUpTopButtons];
    [self setUpCollectionView];
    [self addNotificationToCommentBar];
    [self setUpPlayBar];
    [self setUpCommentBar];
}

#pragma mark - 处理数据
- (void)handleData {
    // 主播页内容请求
    [GXNetTool GET:kDJURL(0, 1, 0) andBody:nil andHeader:nil andResponse:GXJSON andSuccessBlock:^(id result) {
        // 转数据模型
        DJRootModel *djContent = [DJRootModel modelWithDictionary:result];
        self.djContent = djContent;
    } andFailureBlock:^(NSError *error) {
        NSLog(@"主播页内容请求失败");
    }];
    // 主播页地区请求
    [GXNetTool GET:kDJLocationURL andBody:nil andHeader:nil andResponse:GXJSON andSuccessBlock:^(id result) {
        DJLocationRoot *location = [DJLocationRoot modelWithDictionary:result];
        self.djLocation = location;
    } andFailureBlock:^(NSError *error) {
        NSLog(@"主播页地区请求失败");
    }];
    // 电台页内容请求
    [GXNetTool GET:kRadioURL(0, 0, 0) andBody:nil andHeader:nil andResponse:GXJSON andSuccessBlock:^(id result) {
        RadioRootModel *radio = [RadioRootModel modelWithDictionary:result];
        self.radio = radio;
    } andFailureBlock:^(NSError *error) {
        NSLog(@"电台页内容请求失败");
    }];
    // 节目页内容请求
    [GXNetTool GET:kProgramURL(0, 0, 1, 0) andBody:nil andHeader:nil andResponse:GXJSON andSuccessBlock:^(id result) {
        ProgramModel *program = [ProgramModel modelWithDictionary:result];
        self.program = program;
    } andFailureBlock:^(NSError *error) {
        NSLog(@"节目页内容请求失败");
    }];
    // 检测登录
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user objectForKey:@""]) {
        
    }
}

#pragma mark - model setter
- (void)setDjContent:(DJRootModel *)djContent {
    _djContent = djContent;
    [self.collectionView reloadData];
}

- (void)setDjLocation:(DJLocationRoot *)djLocation {
    _djLocation = djLocation;
}

- (void)setRadio:(RadioRootModel *)radio {
    _radio = radio;
}

- (void)setProgram:(ProgramModel *)program {
    _program = program;
}

#pragma mark - 顶部按钮
- (void)setUpTopButtons {
    // 高度为44
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    _topTitles = @[@"我的", @"主播", @"电台", @"节目"];
    CGFloat labelW = SCREEN_WIDTH / 4.0;
    CGFloat labelH = 14;
    CGFloat buttnW = 30;
    for (int i = 0; i < 4; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(i * labelW, buttnW, labelW, labelH)];
        label.text = _topTitles[i];
        label.textColor = [UIColor lightGrayColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:10];
        GX_Button *button = [GX_Button buttonWithType:UIButtonTypeCustom];

        button.frame = CGRectMake(0, 0, buttnW, buttnW);
        button.gx_centerX = label.gx_centerX;
        [button setAdjustsImageWhenHighlighted:NO];
        [button addTarget:self action:@selector(scrollToNextItem:) forControlEvents:UIControlEventTouchUpInside];
        [label setTag:i + 50];
        [button setTag:i + 100];
        [_topView addSubview:label];
        [_topView addSubview:button];
    }
    GX_Button *first = [_topView viewWithTag:100];
    GX_Button *secnd = [_topView viewWithTag:101];
    GX_Button *third = [_topView viewWithTag:102];
    GX_Button *forth = [_topView viewWithTag:103];
    [first setBackgroundImage:[UIImage imageNamed:@"menu_personal_nor"] forState:UIControlStateNormal];
    [first setBackgroundImage:[UIImage imageNamed:@"menu_personal_hl"] forState:UIControlStateSelected];
    [secnd setBackgroundImage:[UIImage imageNamed:@"menu_dj_nor"] forState:UIControlStateNormal];
    [secnd setBackgroundImage:[UIImage imageNamed:@"menu_dj_hl"] forState:UIControlStateSelected];
    [third setBackgroundImage:[UIImage imageNamed:@"menu_radio_nor"] forState:UIControlStateNormal];
    [third setBackgroundImage:[UIImage imageNamed:@"menu_radio_hl"] forState:UIControlStateSelected];
    [forth setBackgroundImage:[UIImage imageNamed:@"menu_show_nor"] forState:UIControlStateNormal];
    [forth setBackgroundImage:[UIImage imageNamed:@"menu_show_hl"] forState:UIControlStateSelected];
    self.navigationItem.titleView = _topView;
}

#pragma mark - Navigation button 点击button切换页面
- (void)scrollToNextItem:(GX_Button *)button {
    for (UIView *view in self.topView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            button.selected = NO;
        } else if ([view isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)view;
            label.textColor = [UIColor lightGrayColor];
        }
    }
    button.selected = YES;
    UILabel *label = [self.topView viewWithTag:button.tag - 50];
    label.textColor = kDefaultColor;
    [self.collectionView setContentOffset:CGPointMake(SCREEN_WIDTH * (button.tag - 100), 0) animated:YES];
}

#pragma mark - 创建cellectionView
- (void)setUpCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    _collectionView.bounces = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor whiteColor];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, _collectionView.gx_height);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 注册cell
    kCollectionViewRegisterNib(@"MineCollectionViewCell", kMineCollectionViewCell);
    kCollectionViewRegisterNib(@"DJCollectionViewCell", kDJCollectionViewCell);
    kCollectionViewRegisterNib(@"RadioCollectionViewCell", kRadioCollectionViewCell);
    kCollectionViewRegisterNib(@"ProgramCollectionViewCell", kProgramCollectionViewCell);
    // 检测collectionView偏移量
    [_collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"kkkk"];
    [self.view addSubview:_collectionView];
}

#pragma mark - 监测CollectionView的偏移量
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    for (UIView *view in self.topView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            button.selected = NO;
        } else if ([view isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)view;
            label.textColor = [UIColor lightGrayColor];
        }
    }
    CGFloat newX = [[change objectForKey:@"new"] CGPointValue].x;
    NSInteger newTag = (newX + SCREEN_WIDTH / 2) / SCREEN_WIDTH;
    UIButton *newButton = [self.topView viewWithTag:newTag + 100];
    UILabel *newLabel = [self.topView viewWithTag:newTag + 50];
    newLabel.textColor = kDefaultColor;
    newButton.selected = YES;
}

#pragma mark - collectionView cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        DJCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDJCollectionViewCell forIndexPath:indexPath];
        if (_djContent) {
            cell.content = _djContent;
            cell.location = _djLocation;
        }
        return cell;
    } else if (indexPath.row == 2) {
        RadioCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kRadioCollectionViewCell forIndexPath:indexPath];
        if (_radio) {
            cell.root = _radio;
        }
        return cell;
    } else if (indexPath.row == 3) {
        ProgramCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kProgramCollectionViewCell forIndexPath:indexPath];
        if (_program) {
            cell.root = _program;
        }
        return cell;
    } else {
        MineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kMineCollectionViewCell forIndexPath:indexPath];
        /**
         * 我的界面的数据
         */
        return cell;
    }
}

- (void)setUpPlayBar {
   /*
    * 添加播放条
    */
    self.playerView = [[PlayBarView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
    [_playerView play:^(GX_Button *play) {
        /**
         * 播放
         */
        NSLog(@"click to play");
    } pause:^(GX_Button *pause) {
        /**
         * 暂停
         */
        NSLog(@"click to pause");
    } listOn:^(GX_Button *listOff) {
        /**
         * 展开
         */
        [self showPlayListMenu];
        [self darkBackground];
    } listOff:^(GX_Button *listOff) {
        /**
         * 收起
         */
        [self hidePlayListMenu];
        [self lightBacground];
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(gotoPlayVC:)];
    [_playerView addGestureRecognizer:tap];
    // 添加观察事件, 当收到消息时隐藏播放条
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(hidePlayerViewAction:)
                                                 name:@"hidePlayerView"
                                               object:@"playerView"];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showPlayerViewAction:)
                                                 name:@"showPlayerView"
                                               object:@"playerView"];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getAudioData:)
                                                 name:@"play"
                                               object:@"dj"];
    [[[UIApplication sharedApplication] keyWindow] addSubview:_playerView];
    [self createPlayListMenu];

}

#pragma mark - 获取播放信息
- (void)getAudioData:(NSNotification *)noti {
    self.record_plays = noti.userInfo[@"model"];
    self.playerView.tittleLabel.text = _record_plays.record[0].record_title;
    [self.playerView.imageView sd_setImageWithURL:[NSURL URLWithString:_record_plays.record_play_image_url] placeholderImage:[UIImage imageNamed:@"placeholderimage"]];
    self.playerView.detailLabel.text = [NSString stringWithFormat:@"%@ %@", _record_plays.record_play_name, _record_plays.record[0].record_file_duration];
}

#pragma mark - 隐藏播放条
- (void)hidePlayerViewAction:(NSNotification *)noti {
    self.playerView.transform = CGAffineTransformMakeScale(0, 49);
}

#pragma mark - 显示播放条
- (void)showPlayerViewAction:(NSNotification *)noti {
    self.playerView.transform = CGAffineTransformIdentity;
}

#pragma mark - 跳转播放界面
- (void)gotoPlayVC:(UITapGestureRecognizer *)tap {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hidePlayerView"
                                                        object:@"playerView"
                                                      userInfo:nil];
    PlayerViewController *playVC = [[PlayerViewController alloc] init];
#warning 这里需要传一个model过去
    
    
    playVC.record_plays = self.record_plays;
    
    
    playVC.view.backgroundColor = [UIColor whiteColor];
#warning modal VC like push animation
    /**
     * 模态实现push动画效果
     */
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.2];
    [animation setType:kCATransitionMoveIn];
    [animation setSubtype:kCATransitionFromTop];
    /**
     * 动画添加的位置，是直接加在window的layer层上，不是当前view的layer层上，如果加在view的layer层是没有那个推的效果的
     */
    [[[[UIApplication sharedApplication] keyWindow] layer] addAnimation:animation forKey:nil];
     /* NO表示把系统的模态跳的动画给关闭，用我们自定义的动画来做 */
    [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:playVC animated:YES completion:nil];
}

#pragma mark - 播放列表菜单
- (void)createPlayListMenu {
    self.playListMenu = [[PlayBarDetailView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 251)];
    _playListMenu.backgroundColor = [UIColor whiteColor];
    [[[UIApplication sharedApplication] keyWindow] insertSubview:_playListMenu belowSubview:_playerView];
}

#pragma mark - 弹出播放列表
- (void)showPlayListMenu {
    [UIView animateWithDuration:0.5 animations:^{
        _playListMenu.transform = CGAffineTransformMakeTranslation(0, -300);
    }];
}

#pragma mark - 隐藏播放列表
- (void)hidePlayListMenu {
    [UIView animateWithDuration:0.5 animations:^{
        _playListMenu.transform = CGAffineTransformIdentity;
    }];
}

- (void)darkBackground {
    _backView.alpha = 0.5;
}

- (void)lightBacground {
    _backView.alpha = 0;
}

#warning 这里没有改变button的状态, 有问题
- (void)tapToHidePlayList {
    [self lightBacground];
    [self hidePlayListMenu];
}

#pragma mark - 评论条
- (void)setUpCommentBar {
    /* 评论条 */
    self.commentBar = [[CommentBar alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 49)];
    /* emoji */
    [_commentBar.emojiBtn addTarget:self action:@selector(emojiBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    _commentBar.textField.delegate = self;
    /* 输入框 */
    [[[UIApplication sharedApplication] keyWindow] insertSubview:_commentBar belowSubview:_playerView];
}

#pragma mark -
- (void)emojiBtnClicked:(GX_Button *)button {
    NSLog(@"emoji");
}

#pragma mark - noti
- (void)hideCommentBar:(NSNotification *)noti {
    [UIView animateWithDuration:0.25 animations:^{
        _commentBar.gx_y = SCREEN_HEIGHT;
    }];
    NSLog(@"%@", noti);
}

- (void)showCommentBar:(NSNotification *)noti {
    [UIView animateWithDuration:0.25 animations:^{
        _commentBar.gx_y = SCREEN_HEIGHT - 49;
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_commentBar.textField endEditing:YES];
    return YES;
}

- (void)moveUpCommentBar:(NSNotification *)noti {
    CGFloat height = [[noti.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].size.height;
    _commentBar.gx_y = SCREEN_HEIGHT - height - 49;
}

- (void)moveDownCommentBar:(NSNotification *)noti {
    CGFloat height = [[noti.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].size.height;
    _commentBar.gx_y = SCREEN_HEIGHT - 49;
}

- (void)addNotificationToCommentBar {
    /**
     * 与键盘同步
     */
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moveUpCommentBar:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moveDownCommentBar:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    /**
     * 控制隐藏和显示
     */
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(hideCommentBar:)
                                                 name:@"hideCommentBar"
                                               object:@"commentBar"];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showCommentBar:)
                                                 name:@"showCommentBar"
                                               object:@"commentBar"];
}

@end
